package cn.z2huo.datastructure.tree.traverseBinaryTree;

import cn.z2huo.datastructure.tree.node.Node;

import java.util.LinkedList;
import java.util.Queue;

/**
 * 层次遍历二叉树
 * @author bouncyslime
 * @date 2021/1/18
 */
public class BinaryTreeTraversing_level {

    /**
     * 使用队列对二叉树进行层次遍历
     * @param root 根结点
     */
    public <T> void traverse(Node<T> root){
        Queue<Node<T>> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()){
            Node<T> node = queue.poll();
            System.out.print((node == null ? "Na" : node.getData()) + " | ");
            if (node != null){
                queue.offer(node.getLeft());
                queue.offer(node.getRight());
            }
        }
    }

    public static void main(String[] args) {
        Integer[] integers = {1, 2, 3, 4, 5, null, null, null, null, 6, 7};
        Node<Integer> root = BinaryTreeUtils.createBinaryTreeFromArray(integers);

        BinaryTreeTraversing_level traversing = new BinaryTreeTraversing_level();

        traversing.traverse(root);

        System.out.println();
    }
}
